package com.chookss.tools

import android.text.TextUtils
import com.chookss.tiku.response.BaseResponse
import com.chookss.tools.old.SignUtils
import com.johnrambo.ktea.common.*
import com.johnrambo.ktea.common.klogutil.KLog
import com.johnrambo.ktea.net.http.HTTP
import com.johnrambo.ktea.net.http.Method
import kotlinx.coroutines.Job
import org.greenrobot.eventbus.EventBus

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/15 11:03
 * Note:
 */

class NetWrapper2<T> {
    lateinit var url: String
    var method: Method? = null
    var params: MutableMap<String, Any?>? = mutableMapOf()

    var onSuccess: ((result: T) -> Unit)? = null
    var onError: ((error: String) -> Unit)? = null
    var onErrorFull: ((error: String, result: T?) -> Unit)? = null
}

inline fun <reified T : BaseResponse> httpForm(crossinline config: NetWrapper2<T>.() -> Unit): Job {
    val wrapper2 = NetWrapper2<T>()
    wrapper2.config()
    return launchIO {
        var result = httpFormIOInner(wrapper2)
        launchUI {
            if (result.isSuccess) {
                wrapper2.onSuccess?.invoke(result)
            } else {
                if(!Utils.isNull(result.msg)&&result.code.toString().startsWith("400")){
                    if(result.msg.contains("签名")||result.msg.contains("超时")||result.msg.contains("失效")||result.msg.contains("accessToken")){
                        EventBus.getDefault().post(MyEvent("Failure"))
                    }
                }
                wrapper2.onErrorFull?.invoke(result.msg, result)
                wrapper2.onError?.invoke(result.msg!!)
            }
        }.join()
    }
}

inline fun <reified T : BaseResponse> httpFormIO(crossinline config: NetWrapper2<T>.() -> Unit): T {
    val wrapper2 = NetWrapper2<T>()
    wrapper2.config()
    return httpFormIOInner(wrapper2)
}

inline fun <reified T : BaseResponse> httpFormIOInner(wrapper2: NetWrapper2<T>): T {
    wrapper2.method = wrapper2.method ?: Method.POST
    with(wrapper2) {
        var result: String? = null
        var error: String? = null
        var resultObject: T? = null
        try {
            val timestamp = SignUtils.getTimeStamp() //20201208125238
            val nonce = SignUtils.getRandomString(14)
            val sign = SignUtils.makeSignStr(params, timestamp, nonce, false)
            logger("sign:$sign")
            params!!["sign"] = sign
            val response = HTTP.execute(method!!, url, params)
            if (response.isSuccessful) {
                try {
                    result = response.body()!!.string().trim()
                    resultObject = result.parseObject<T>()
                } catch (e: java.lang.Exception) {
                    error = "数据解析失败"
                }
            } else {
                KLog.i("code:${response.code()} ; 连接错误:${response.errorBody()!!.string()}")
                error = "连接错误"
            }
        } catch (e: Exception) {
            error = Utils.onErrorTips(e.message)
        }

        if (resultObject == null) {
            resultObject = "{}".parseObject<T>()
        }

        if (!resultObject!!.isSuccess) {
            if (TextUtils.isEmpty(resultObject.msg)) {
                resultObject.msg = error ?: "服务器异常，请稍后重试"
            }
        }
        return@httpFormIOInner resultObject
    }

}
